import 'package:date_format/date_format.dart';
import 'package:elevator/db/db_helper.dart';
import 'package:elevator/db/error_data.dart';
import 'package:elevator/get/intl_keys.dart';
import 'package:elevator/pages/home/all/detail_new/pages/errors/errors_view.dart';
import 'package:elevator/pages/home/all/detail_new/pages/errors/operate/operate_view.dart';
import 'package:elevator/utils/eventbus.dart';
import 'package:elevator/utils/utils_logger.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_expandable_table/flutter_expandable_table.dart';
import 'package:get/get.dart';
import 'package:mysql1/mysql1.dart' as mysql;

class ErrorsLogic extends GetxController {
  late String buildId;
  late String liftId;
  var errorData = <ErrorData>[].obs;
  late ExpandableTableController controller;
  double itemWidth = 120;
  final int columnsCount = 3;
  int index = 1;
  late List<ExpandableTableRow> tableRows;

  @override
  void onReady() {
    // TODO: implement onReady
    String date = formatDate(DateTime.now(), [yyyy, '-', mm, '-', dd]);
    queryBuildErrorData(buildId,date,date);
    bus.on(bus.errorTimePickedKey, busCallback);
    super.onReady();
    initTableController();
    logd('-------errors onReady');
  }

  void initTableController() {
    tableRows = List.generate(
      errorData.length,
          (rowIndex) => ExpandableTableRow(
        height: 50,
        firstCell: _buildCell(rowIndex),
        cells: List<ExpandableTableCell>.generate(
          columnsCount - 1,
              (columnIndex) => _buildCell2(rowIndex, columnIndex),
        ),
      ),
    );
    controller = ExpandableTableController(
      firstHeaderCell: buildFirstCell(IntlKeys.errorReCordTimeTitle.tr),
      firstColumnWidth: itemWidth,
      headers: [
        ExpandableTableHeader(
          width: itemWidth,
          cell: buildFirstCell(IntlKeys.errorCodeTitle.tr),
        ),
        ExpandableTableHeader(
          width: itemWidth,
          cell: buildFirstCell(IntlKeys.errorNameTitle.tr),
        ),
      ],
      rows: tableRows,
      headerHeight: 63,
    );
  }

  ExpandableTableCell buildFirstCell(String content, {CellBuilder? builder}) {
    return ExpandableTableCell(
      child: builder != null
          ? null
          : DefaultCellCard(
        child: Container(
          // color: Colors.yellowAccent,
          child: GestureDetector(
            onTap: () {
              print('点击项目$content');

            },
            child: Center(
              child: Text(
                content,
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
        ),
      ),
      builder: builder,
    );
  }

  ExpandableTableCell _buildCell2(int row, int col, {CellBuilder? builder}) {
    String content = '';

    if (col == 0) {
      content = errorData[row].fErrorCode ?? '';
    } else if (col == 1) {
      content = errorData[row].fErrorName ?? '';
    }

    return ExpandableTableCell(
      child: builder != null
          ? null
          : DefaultCellCard(
        child: Container(
          // color: Colors.yellowAccent,
          child: GestureDetector(
            onTap: () {
              print('点击项目$content');
              Get.to(OperatePage(
                title: content,
                errorData: errorData[row],
              ));
            },
            child: Center(
              child: Text(
                content,
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
        ),
      ),
      builder: builder,
    );
  }


  /// 查询错误信息
  queryBuildErrorData(String buildId,String startDate,String endDate ) async {
    debugPrint("start queryBuildErrorData $buildId");
    var settings = mysql.ConnectionSettings(
        host: '36.141.45.30',
        port: 43306,
        user: 'root',
        password: 'adminemqx123',
        db: 'liftdb_$buildId',
        useCompression: false,
        timeout:const Duration(seconds: 60),
        maxPacketSize:16 * 1024 * 1024 *1024,
        characterSet: mysql.CharacterSet.UTF8MB4);
    var conn = await mysql.MySqlConnection.connect(settings);

    var errorDataResluts = await conn
        .query("select * from tbtpcerrcode WHERE fDateTime between '$startDate 00:00:00' and '$endDate 23:59:59' and liftAdr = '$liftId'");

    List<ErrorData> errorDatas = [];
    for (var row in errorDataResluts) {
      if(row.length>=4){
        ErrorData error = ErrorData.builder(row);
        errorDatas.add(error);
      }
    }
    conn.close();
    errorData.value = errorDatas;
    debugPrint("楼盘 $buildId errorData加载1$startDate至$endDate完毕：${errorData.length}条");
    errorData.refresh();
    debugPrint("楼盘 $buildId errorData加载$startDate至$endDate完毕：${errorData.length}条");
    if (errorDatas.isEmpty) {
      for (int i = 0; i < index; i++) {
        errorDatas.add(ErrorData(
          ID: i,
          fDateTime: DateTime.now(),
          fErrorCode: 'code $i',
          fErrorName: 'name $i',
        ));
      }

    }
    index ++;

    controller.rows.addAll(addRowsDate(errorDatas));
    update();
  }

  List<ExpandableTableRow> addRowsDate(List<ErrorData> errorData) {
    final List<ExpandableTableRow> rows = List.generate(
      errorData.length,
          (rowIndex) => ExpandableTableRow(
        height: 50,
        firstCell: _buildCell(rowIndex),
        cells: List<ExpandableTableCell>.generate(
          columnsCount - 1,
              (columnIndex) => _buildCell2(rowIndex, columnIndex),
        ),
      ),
    );
    logd('----add ${rows.length}');
    return rows;
  }

  busCallback(var pickedTimes) {
    if (pickedTimes != null && pickedTimes.length==2) {
      String startDate = formatDate(pickedTimes[0], [yyyy, '-', mm, '-', dd]);
      String endDate = formatDate(pickedTimes[1], [yyyy, '-', mm, '-', dd]);
      queryBuildErrorData(buildId,startDate,endDate);
    }
  }

  ExpandableTableCell _buildCell(int index, {CellBuilder? builder}) {
    String content = formatDate(errorData[index].fDateTime ?? DateTime.now(), [yyyy, '-', mm, '-', dd ," ",HH ,":",nn,":",ss]);
    return ExpandableTableCell(
      child: builder != null
          ? null
          : DefaultCellCard(
        child: Container(
          // color: Colors.yellowAccent,
          child: GestureDetector(
            onTap: () {
              print('点击项目$content');
              Get.to(OperatePage(
                title: content,
                errorData: errorData[index],
              ));
            },
            child: Center(
              child: Text(
                content,
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
        ),
      ),
      builder: builder,
    );
  }


  @override
  void onClose() {
    bus.off(bus.errorTimePickedKey, busCallback);
  }

}
